<template>
    <div class="container" style="background:white">
        <div class="row">
            <div class="col-md-12">
                <header>
                    <h1>微博详情</h1>
                </header>
            </div>
        </div>
        <div class="row">
            <!-- 微博详情 -->
            <div class="col-md-9">
                <!-- 评论区 -->
                <div class="panel panel-default" style="margin-top:20px">
                    <div class="panel-heading">评论区</div>
                    <div class="panel-body">
                        <!-- 评论列表 -->
                        <ul class="list-group">
                            <li v-for="(comment, index) in comments" :key="index" class="list-group-item">
                                {{ comment.userName }}: {{ comment.content }}
                                <td>
				<button class="btn btn-primary" @click="navigateToDetail(comment.weiboId)">微博详情</button>
			  </td>
                            </li>
                        </ul>
                        <!-- 发表评论 -->
                        <form @submit.prevent="submitComment">
                            <div class="form-group">
                                <div class="col-sm-12">
                                    <textarea v-model="commentContent" id="txt" class="form-control"
                                        rows="3"></textarea>
                                </div>
                            </div>
                            <div class="form-group">
                                <div class="col-sm-12">
                                    <button type="submit" class="btn btn-default">提交</button>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
            <!-- 右侧布局 -->
            <div class="col-md-3">
                <!-- 个人信息 -->
                <div class="thumbnail">
                    <img src="../imgs/7.jpg" alt="..." class="img-circle" width="100px" height="120px"
                        style="float:left;margin:30px 10px">
                    <div class="caption text-center">
                        <p><strong></strong> {{ userName }}</p>
                        <p>发表博文:102</p>
                        <p>
                            <button @click="handleFollow" class="btn btn-primary" role="button">
                                {{ isFollowing ? '取消关注' : '关注' }}
                            </button>
                        </p>
                    </div>
                </div>
                <!-- 排行榜 -->
                <div class="list-group">
                    <a href="#" class="list-group-item" style="background:#008;color:white">作者的博客</a>
                    <a href="#" class="list-group-item"><span class="badge">20</span>Dapibus ac facilisis in</a>
                    <a href="#" class="list-group-item"><span class="badge">30</span>Morbi leo risus</a>
                    <a href="#" class="list-group-item"><span class="badge">98</span>Porta ac consectetur ac</a>
                    <a href="#" class="list-group-item"><span class="badge">69</span>Vestibulum at eros</a>
                </div>
            </div>
        </div>
    </div>
</template>
<script>
import { reactive, toRefs } from "vue";
import { useRoute } from "vue-router";
import axios from "axios";
import { onMounted } from 'vue';
import { getSessionStorage } from "@/common";
import router from "@/router";

export default {
    name: "Detail2",
    setup() {
        const route = useRoute();
        const state = reactive({
            weiboId: route.query.weiboId,
            userName: '',
            weiboTitle: '',
            weiboContent: '',
            createTime: '',
            readCount: 0,
            img: '',
            loginName: getSessionStorage("user").loginName,
            comments: [],
            commentContent: '',
            pageNum: 1,
            pageSize: 100,
            commentState: 1,
            isFollowing: false // 新增状态用于管理按钮的文本
        });

        onMounted(async () => {
            await getComments(state.pageNum, state.pageSize, state.loginName, state.commentState);
            await checkFollowingStatus(); // 检查是否已关注
        });


        async function getComments(pageNum, pageSize, loginName, commentState) {
            try {
                const response = await axios.get("http://localhost:81/xw01/xw-weibo/api/weibo/getWeiboListByLoginName", {
                    params: { pageNum, pageSize, loginName, state: commentState }
                });
                console.log(response.data);
                let arr = [];

                for (let i = 0; i < response.data.data.records.length; i++) {
                    for (let j = 0; j < response.data.data.records[i].map.commentList.length; j++) {
                        arr.push({
                            weiboId: response.data.data.records[i].weiboId,
                            userName: response.data.data.records[i].userName,
                            commentId: response.data.data.records[i].map.commentList[j].commentId,
                            content: response.data.data.records[i].map.commentList[j].content,
                            createTime: response.data.data.records[i].map.commentList[j].createTime,
                        })

                    }
                }
                state.comments = arr;
                sortByKey(state.comments, 'createTime');
                console.log(state.comments );

            } catch (error) {
                console.error(error);
            }
        }

        function sortByKey(array, key) {
            if (array)
                return array.sort(function (b, a) {

                    var x = a[key];
                    var y = b[key];
                    return ((x < y) ? -1 : ((x < y) ? 1 : 0));
                });
        }


        //   async function submitComment() {
        //     const user = JSON.parse(sessionStorage.getItem('user'));
        //     const userloginname = user.loginName;
        //     const wbid = state.weiboId;
        //     const content = state.commentContent;

        //     try {
        //       const response = await axios.get("http://localhost:81/xw01/xw-comment/api/comment/addComment", {
        //         params: {
        //           wbid,
        //           content,
        //           userloginname
        //         }
        //       });

        //       if (response.data.code === 200) {
        //         alert("评论成功");
        //         state.comments.push(response.data.data);
        //         state.commentContent = '';
        //       } else {
        //         alert("评论失败: " + response.data.msg);
        //       }
        //     } catch (error) {
        //       console.error(error);
        //       alert("评论失败: 网络错误或服务器无响应");
        //     }
        //   }

        //   async function checkFollowingStatus() {
        //     const user = JSON.parse(sessionStorage.getItem('user'));
        //     const attentionName = user.loginName;
        //     const userName = state.userName;

        //     try {
        //       const response = await axios.get("http://localhost:81/xw01/xw-attention/api/attention/checkFollowingStatus", {
        //         params: { attentionName, userName }
        //       });
        //       if (response.data.code === 200 && response.data.data) {
        //         state.isFollowing = true;
        //       } else {
        //         state.isFollowing = false;
        //       }
        //     } catch (error) {
        //       console.error(error);
        //     }
        //   }

        async function handleFollow() {
            const user = JSON.parse(sessionStorage.getItem('user'));
            const userName = state.userName; // 获取当前微博作者的用户名
            const attentionName = user.loginName; // 当前登录用户的登录名

            try {
                const response = await axios.get("http://localhost:81/xw01/xw-attention/api/attention/addAttention", {
                    params: {
                        attentionName,
                        userName
                    }
                });

                if (response.data.code === 200) {
                    state.isFollowing = !state.isFollowing;
                    alert(state.isFollowing ? "关注成功" : "取消关注成功");
                    // 可以根据需要更新页面或者执行其他操作
                } else {
                    alert("操作失败: " + response.data.msg);
                }
            } catch (error) {
                console.error(error);
                alert("操作失败: 网络错误或服务器无响应");
            }
        }

        function navigateToDetail(weiboId) {
        console.log(weiboId);
            router.push({ 
                path: '/detail2', 
                query: { weiboId: weiboId} 
            });
        }

        return {
            ...toRefs(state),
            handleFollow,
            sortByKey,
            navigateToDetail
        }
    }
}
</script>


<style scoped>
/* Add your styles here */
</style>